﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IdentityModel;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Security;
using Microsoft.Xrm.Sdk.Query;
using System.Diagnostics;
using System.ServiceModel.Description;
using AppConfiguration;
using EncryptionUtility;
using Microsoft.Crm.Sdk.Messages;

namespace XRMServiceLibrary
{
    public enum ErrorlogType
    {
        WriteLog,
        EmailLog,
        Both,
    }

    public abstract class baseCRMService
    {
        public OrganizationServiceProxy serviceProxy;
        public IOrganizationService iOrgService;

        public static String LogFilePath;
        public static Object sender;
        protected MethodBase methodBase;
        public static String sUserID;
        public baseCRMService()
        {
            try
            {
                // Connect to the Organization service.    
                ClientCredentials credentials = new ClientCredentials();
                Uri homeRealmUri = null;
                //string username = ConfigReader.GetInstance().AutoUpdateUserName;                                   //Comment this 2 after going to prod
                //string password = ConfigReader.GetInstance().AutoUpdatePassword;
                string username = ConfigReader.GetInstance().AdminUserName;                                   //Comment this 2 after going to prod
                string password = ConfigReader.GetInstance().AdminPassword;
                //string username = EncryptionManager.Decrypt(ConfigReader.GetInstance().EncryptedAdminUserName); //Uncomment this 2 after going to Prod
                //string password = EncryptionManager.Decrypt(ConfigReader.GetInstance().EncryptedAdminPassword);
                credentials.Windows.ClientCredential = new System.Net.NetworkCredential(username, password, ConfigReader.GetInstance().AdminDomain);
                OrganizationServiceProxy orgProxy = new OrganizationServiceProxy(new Uri(ConfigReader.GetInstance().OrganizationUri.ToString()), homeRealmUri, credentials, null);
                orgProxy.Timeout = new TimeSpan(0, 10, 0);
                if (!string.IsNullOrEmpty(sUserID))
                {
                    orgProxy.CallerId = new Guid(sUserID);

                }
                serviceProxy = orgProxy;
                orgProxy.EnableProxyTypes();
                iOrgService = (IOrganizationService)orgProxy;
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw ex;
            }
            catch (ExpiredSecurityTokenException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw ex;
            }
            catch (SecurityAccessDeniedException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw ex;
            }
            catch (MessageSecurityException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw ex;
            }
            catch (SecurityNegotiationException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw ex;
            }

        }

    }

    public class CRMServiceUtilities : baseCRMService
    {
        public Int32 ErrorlogType = 1;
        const string _defaultValue = "00000000-0000-0000-0000-000000000000";

        public OrganizationResponse Execute(OrganizationRequest orgRequest)
        {
            OrganizationResponse parentId = new OrganizationResponse();
            try
            {
                {
                    iOrgService = setService();
                }
                parentId = iOrgService.Execute(orgRequest);
            }
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.OrganizationServiceFault, ErrorlogType);
            }
            catch (ExpiredSecurityTokenException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.ExpiredSecurityTokenException, ErrorlogType);
            }
            catch (SecurityAccessDeniedException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityAccessDeniedException, ErrorlogType);
            }
            catch (MessageSecurityException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.MessageSecurityException, ErrorlogType);
            }
            catch (SecurityNegotiationException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityNegotiationException, ErrorlogType);
            }
            catch (Exception ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.Exception);
            }

            return parentId;
        }
        /// <summary>
        /// Create
        /// </summary>
        public Guid Create(Entity bussinessEntity)
        {

            Guid ParentId = new Guid();
            try
            {
                //if (iOrgService == null)
                {
                    //iOrgService = null;
                    iOrgService = setService();
                }
                // Create an account record named Fourth Coffee.
                ParentId = iOrgService.Create(bussinessEntity);
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.OrganizationServiceFault, ErrorlogType);
            }
            catch (ExpiredSecurityTokenException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.ExpiredSecurityTokenException, ErrorlogType);
            }
            catch (SecurityAccessDeniedException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityAccessDeniedException, ErrorlogType);
            }
            catch (MessageSecurityException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.MessageSecurityException, ErrorlogType);
            }
            catch (SecurityNegotiationException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityNegotiationException, ErrorlogType);
            }
            catch (Exception ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.Exception);
            }
            return ParentId;

        }

        /// <summary>
        /// Retrive
        /// </summary>
        public Entity Retrive(string EntityName, Guid Id, ColumnSet ColumnSet)
        {

            Entity RetEntity = new Entity();
            try
            {
                if (iOrgService == null)
                {
                    //iOrgService = null;
                    iOrgService = setService();
                }
                // Create an account record named Fourth Coffee.
                RetEntity = iOrgService.Retrieve(EntityName, Id, ColumnSet);
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.OrganizationServiceFault, ErrorlogType);
            }
            catch (ExpiredSecurityTokenException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.ExpiredSecurityTokenException, ErrorlogType);
            }
            catch (SecurityAccessDeniedException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityAccessDeniedException, ErrorlogType);
            }
            catch (MessageSecurityException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.MessageSecurityException, ErrorlogType);
            }
            catch (SecurityNegotiationException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityNegotiationException, ErrorlogType);
            }
            catch (Exception ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.Exception);
            }
            return RetEntity;
        }

        /// <summary>
        /// RetrieveMultiple
        /// </summary>
        public EntityCollection RetrieveMultiple(QueryBase QueryBase)
        {

            EntityCollection MultiEntity = new EntityCollection();
            try
            {
                if (iOrgService == null)
                {
                    //iOrgService = null;
                    iOrgService = setService();
                }
                // Create an account record named Fourth Coffee.
                MultiEntity = iOrgService.RetrieveMultiple(QueryBase);
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.OrganizationServiceFault, ErrorlogType);
            }
            catch (ExpiredSecurityTokenException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.ExpiredSecurityTokenException, ErrorlogType);
            }
            catch (SecurityAccessDeniedException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityAccessDeniedException, ErrorlogType);
            }
            catch (MessageSecurityException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.MessageSecurityException, ErrorlogType);
            }
            catch (SecurityNegotiationException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityNegotiationException, ErrorlogType);
            }
            catch (Exception ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.Exception);
            }
            return MultiEntity;
        }

        /// <summary>
        /// Update
        /// </summary>
        public void Update(Entity bussinessEntity)
        {

            try
            {
                //if (iOrgService == null)
                {
                    //iOrgService = null;
                    iOrgService = setService();
                }
                StackTrace stackTrace = new StackTrace();
                StackFrame stackFrame = stackTrace.GetFrame(1);
                methodBase = stackFrame.GetMethod();

                iOrgService.Update(bussinessEntity);
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                // Displays “WhatsmyName”
                Console.WriteLine(" Parent Method Name {0} ", methodBase.Name);
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.OrganizationServiceFault, ErrorlogType);
            }
            catch (ExpiredSecurityTokenException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.ExpiredSecurityTokenException, ErrorlogType);
            }
            catch (SecurityAccessDeniedException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityAccessDeniedException, ErrorlogType);
            }
            catch (MessageSecurityException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.MessageSecurityException, ErrorlogType);
            }
            catch (SecurityNegotiationException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityNegotiationException, ErrorlogType);
            }
            catch (Exception ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.Exception, ErrorlogType);
            }
        }

        /// <summary>
        /// Delete
        /// </summary>
        public void Delete(string EntityName, Guid Id)
        {

            try
            {
                // Create an account record named Fourth Coffee.
                //if (iOrgService == null)
                //{
                //iOrgService = null;
                iOrgService = setService();
                //}
                iOrgService.Delete(EntityName, Id);
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.OrganizationServiceFault, ErrorlogType);
            }
            catch (ExpiredSecurityTokenException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.ExpiredSecurityTokenException, ErrorlogType);
            }
            catch (SecurityAccessDeniedException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityAccessDeniedException, ErrorlogType);
            }
            catch (MessageSecurityException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.MessageSecurityException, ErrorlogType);
            }
            catch (SecurityNegotiationException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityNegotiationException, ErrorlogType);
            }
            catch (Exception ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.Exception);
            }
        }

        /// <summary>
        /// AssignRole
        /// </summary>
        /// <param name="UserId">GUID of the user to whom role is to be provided.</param>
        /// <param name="RoleId">Multiple roles can be added using List.</param>
        public void AssignRole(string UserId, List<string> RoleId)
        {
            try
            {
                if (iOrgService == null)
                {
                    //iOrgService = null;
                    iOrgService = setService();
                }
                foreach (string role in RoleId)
                {
                    iOrgService.Associate("systemuser", new Guid(UserId), new Relationship("systemuserroles_association"),

                      new EntityReferenceCollection() { new EntityReference("role", new Guid(role)) });
                }
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.OrganizationServiceFault, ErrorlogType);
            }
            catch (ExpiredSecurityTokenException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.ExpiredSecurityTokenException, ErrorlogType);
            }
            catch (SecurityAccessDeniedException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityAccessDeniedException, ErrorlogType);
            }
            catch (MessageSecurityException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.MessageSecurityException, ErrorlogType);
            }
            catch (SecurityNegotiationException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityNegotiationException, ErrorlogType);
            }
            catch (Exception ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.Exception);
            }
        }

        /// <summary>
        /// RevokeRole
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="RoleId"></param>
        public void RevokeRole(string UserId, List<string> RoleId)
        {
            try
            {
                if (iOrgService == null)
                {
                    //iOrgService = null;
                    iOrgService = setService();
                }
                foreach (string roleid in RoleId)
                {
                    iOrgService.Disassociate("systemuser", new Guid(UserId), new Relationship("systemuserroles_association"),
                      new EntityReferenceCollection() { new EntityReference("role", new Guid(roleid)) });
                }

            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.OrganizationServiceFault, ErrorlogType);
            }
            catch (ExpiredSecurityTokenException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.ExpiredSecurityTokenException, ErrorlogType);
            }
            catch (SecurityAccessDeniedException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityAccessDeniedException, ErrorlogType);

            }
            catch (MessageSecurityException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.MessageSecurityException, ErrorlogType);
            }
            catch (SecurityNegotiationException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityNegotiationException, ErrorlogType);
            }
            catch (Exception ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.Exception);
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="MailTo">MailTo</param>
        /// <param name="MailCC">MailCC</param>
        /// <param name="MailBCC">MailBCC</param>
        /// <param name="MailFrom">MailFrom</param>
        /// <param name="Subject">Subject</param>
        /// <param name="MailBody">MailBody</param>
        /// <param name="RegardingObject">Regarding Object (its a dictonary user should enter the value. First item is entity name and second item is its Record GUID. )</param>
        /// <param name="OwnerId">optional field may be blank</param>
        /// <returns></returns>
        public Guid SendCRMMail(List<string> MailTo, List<string> MailCC, List<string> MailBCC,
            Guid MailFrom, string Subject, string MailBody, Dictionary<string, string> RehardingObject,
            String OwnerId = _defaultValue)
        {
            Guid ParentId = new Guid();
            try
            {
                // Create an e-mail message.
                Email email = new Email();

                List<ActivityParty> CRMMail = new List<ActivityParty>();


                CRMMail = GetMailSender(MailTo);
                if (CRMMail.Count > 0)
                {
                    email.To = CRMMail.ToArray();
                    CRMMail.Clear();
                }

                CRMMail = GetMailSender(MailCC);
                if (CRMMail.Count > 0)
                {
                    email.Cc = CRMMail.ToArray();
                    CRMMail.Clear();
                }

                CRMMail = GetMailSender(MailBCC);
                if (CRMMail.Count > 0)
                {
                    email.Bcc = CRMMail.ToArray();
                    CRMMail.Clear();
                }


                // Create the 'To:' activity party for the email
                ActivityParty from = new ActivityParty
                {
                    PartyId = new EntityReference("systemuser", MailFrom)
                };

                email.From = new ActivityParty[] { from };

                email.Subject = Subject;
                email.Description = MailBody;
                email.DirectionCode = true;

                foreach (KeyValuePair<string, string> kvp in RehardingObject)
                {
                    email.RegardingObjectId = new EntityReference(kvp.Key, new Guid(kvp.Value)); // Order Id
                }

                if (OwnerId != _defaultValue)
                {
                    email.OwnerId = new EntityReference("systemuser", new Guid(OwnerId));
                }

                ParentId = iOrgService.Create(email);
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.OrganizationServiceFault, ErrorlogType);
            }
            catch (ExpiredSecurityTokenException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.ExpiredSecurityTokenException, ErrorlogType);
            }
            catch (SecurityAccessDeniedException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityAccessDeniedException, ErrorlogType);
            }
            catch (MessageSecurityException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.MessageSecurityException, ErrorlogType);
            }
            catch (SecurityNegotiationException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityNegotiationException, ErrorlogType);
            }
            catch (Exception ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.Exception, ErrorlogType);
            }
            return ParentId;
        }


        /// <summary>
        /// GetMailSender
        /// </summary>
        /// <param name="lst"></param>
        /// <returns></returns>
        private List<ActivityParty> GetMailSender(List<string> lst)
        {
            List<ActivityParty> CRMMail = new List<ActivityParty>();
            try
            {
                foreach (string Id in lst)
                {
                    // Create the 'To:' activity party for the email
                    ActivityParty toParty = new ActivityParty
                    {
                        PartyId = new EntityReference("systemuser", new Guid(Id))
                    };
                    CRMMail.Add(toParty);
                }
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.OrganizationServiceFault, ErrorlogType);
            }
            catch (ExpiredSecurityTokenException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.ExpiredSecurityTokenException, ErrorlogType);
            }
            catch (SecurityAccessDeniedException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityAccessDeniedException, ErrorlogType);
            }
            catch (MessageSecurityException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.MessageSecurityException, ErrorlogType);
            }
            catch (SecurityNegotiationException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityNegotiationException, ErrorlogType);
            }
            catch (Exception ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.Exception, ErrorlogType);
            }
            return CRMMail;
        }


        /// <summary>
        /// OwnerChange
        /// </summary>
        /// <param name="EntityName"></param>
        /// <param name="NewOwnerId"></param>
        /// <param name="OrderId"></param>
        public void OwnerChange(String EntityName, String NewOwnerId, List<String> OrderIds)
        {
            try
            {
                //TODO:Pritam
                //This is quick fix code..remove it asap.
                if (iOrgService == null)
                {
                    iOrgService = setService();
                }

                foreach (string Orderid in OrderIds)
                {
                    if (!string.IsNullOrEmpty(EntityName))
                    {
                        AssignRequest assignRequest = new AssignRequest
                        {
                            Assignee = new EntityReference
                            {
                                LogicalName = "systemuser",
                                // Here we could assign the visualization to the newly created user
                                Id = new Guid(NewOwnerId)
                            },

                            Target = new EntityReference
                            {
                                LogicalName = EntityName,
                                Id = new Guid(Orderid)
                            }
                        };
                        serviceProxy = getProxy();
                        serviceProxy.Execute(assignRequest);
                    }
                }

            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.OrganizationServiceFault, ErrorlogType);
            }
            catch (ExpiredSecurityTokenException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.ExpiredSecurityTokenException, ErrorlogType);
            }
            catch (SecurityAccessDeniedException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityAccessDeniedException, ErrorlogType);
            }
            catch (MessageSecurityException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.MessageSecurityException, ErrorlogType);
            }
            catch (SecurityNegotiationException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityNegotiationException, ErrorlogType);
            }
            catch (Exception ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.Exception, ErrorlogType);
            }

        }

        /// <summary>
        /// ProvideFullAccess
        /// </summary>
        /// <param name="entityname"></param>
        /// <param name="recordid"></param>
        /// <param name="userid"></param>
        public void ProvideFullAccess(string entityname, string recordid, string userid)
        {
            var entityReference = new EntityReference(entityname, new Guid(recordid));
            var systemUser1Ref = new EntityReference("systemuser", new Guid(userid));
            int ReadAccess = 0;
            int WriteAccess = 0;
            int AppendAccess = 0;
            int AppendToAccess = 0;
            ReadAccess = (int)AccessRights.ReadAccess;
            WriteAccess = (int)AccessRights.WriteAccess;
            AppendAccess = (int)AccessRights.AppendAccess;
            AppendToAccess = (int)AccessRights.AppendToAccess;
            int i = (ReadAccess + WriteAccess + AppendAccess + AppendToAccess);
            AccessRights privileges = (AccessRights)i;
            var grantAccessRequest1 = new GrantAccessRequest
            {
                PrincipalAccess = new PrincipalAccess
                {
                    AccessMask = privileges,
                    Principal = systemUser1Ref
                },
                Target = entityReference
            };
            try
            {
                //if (iOrgService == null)
                iOrgService = setService();
                iOrgService.Execute(grantAccessRequest1);
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.OrganizationServiceFault, ErrorlogType);
            }
            catch (ExpiredSecurityTokenException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.ExpiredSecurityTokenException, ErrorlogType);
            }
            catch (SecurityAccessDeniedException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityAccessDeniedException, ErrorlogType);
            }
            catch (MessageSecurityException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.MessageSecurityException, ErrorlogType);
            }
            catch (SecurityNegotiationException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityNegotiationException, ErrorlogType);
            }
            catch (Exception ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.Exception);
            }

        }

        /// <summary>
        /// RevokeAccess
        /// </summary>
        /// <param name="entityname"></param>
        /// <param name="recordid"></param>
        /// <param name="userid"></param>
        public void RevokeAccess(string entityname, string recordid, string userid)
        {
            var entityReference = new EntityReference(entityname, new Guid(recordid));
            var systemUser1Ref = new EntityReference("systemuser",
                    new Guid(userid));
            int ReadAccess = 0;
            int WriteAccess = 0;
            int AppendAccess = 0;
            int AppendToAccess = 0;
            ReadAccess = (int)AccessRights.ReadAccess;
            WriteAccess = (int)AccessRights.WriteAccess;
            AppendAccess = (int)AccessRights.AppendAccess;
            AppendToAccess = (int)AccessRights.AppendToAccess;
            int i = (ReadAccess + WriteAccess + AppendAccess + AppendToAccess);
            AccessRights privileges = (AccessRights)i;
            var revokeAccessRequest1 = new RevokeAccessRequest
            {
                Revokee = systemUser1Ref,
                Target = entityReference

            };
            try
            {
                if (iOrgService == null)
                    iOrgService = setService();
                iOrgService.Execute(revokeAccessRequest1);
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.OrganizationServiceFault, ErrorlogType);
            }
            catch (ExpiredSecurityTokenException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.ExpiredSecurityTokenException, ErrorlogType);
            }
            catch (SecurityAccessDeniedException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityAccessDeniedException, ErrorlogType);
            }
            catch (MessageSecurityException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.MessageSecurityException, ErrorlogType);
            }
            catch (SecurityNegotiationException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityNegotiationException, ErrorlogType);
            }
            catch (Exception ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.Exception);
            }

        }

        /// <summary>
        /// setService   like GetCRMService
        /// </summary>
        /// <returns></returns>
        protected IOrganizationService setService()
        {
            try
            {
                ClientCredentials credentials = new ClientCredentials();
                Uri homeRealmUri = null;
                //string username = ConfigReader.GetInstance().AutoUpdateUserName;                                   //Comment this 2 after going to prod
                //string password = ConfigReader.GetInstance().AutoUpdatePassword;
                string username = ConfigReader.GetInstance().AdminUserName;                                   //Comment this 2 after going to prod
                string password = ConfigReader.GetInstance().AdminPassword;
                //string username = EncryptionManager.Decrypt(ConfigReader.GetInstance().EncryptedAdminUserName);
                //string password = EncryptionManager.Decrypt(ConfigReader.GetInstance().EncryptedAdminPassword);
                credentials.Windows.ClientCredential = new System.Net.NetworkCredential(username, password, ConfigReader.GetInstance().AdminDomain);
                OrganizationServiceProxy orgProxy = new OrganizationServiceProxy(new Uri(ConfigReader.GetInstance().OrganizationUri.ToString()), homeRealmUri, credentials, null);
                orgProxy.Timeout = new TimeSpan(0, 10, 0);
                if (!string.IsNullOrEmpty(sUserID))
                {
                    orgProxy.CallerId = new Guid(sUserID);
                }
                orgProxy.EnableProxyTypes();
                iOrgService = (IOrganizationService)orgProxy;
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.OrganizationServiceFault);
            }
            catch (ExpiredSecurityTokenException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.ExpiredSecurityTokenException);
            }
            catch (SecurityAccessDeniedException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityAccessDeniedException);
            }
            catch (MessageSecurityException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.MessageSecurityException);
            }
            catch (SecurityNegotiationException ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.SecurityNegotiationException);
            }
            catch (Exception ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                BaseLogger.LogError(ex, (int)ExceptionType.Exception);
            }
            return iOrgService;
        }

        public OrganizationServiceProxy getProxy()
        {
            ClientCredentials credentials = new ClientCredentials();
            Uri homeRealmUri = null;
            //string username = ConfigReader.GetInstance().AutoUpdateUserName;                                   //Comment this 2 after going to prod
            //string password = ConfigReader.GetInstance().AutoUpdatePassword;
            string username = ConfigReader.GetInstance().AdminUserName;                                   //Comment this 2 after going to prod
            string password = ConfigReader.GetInstance().AdminPassword;
            //string username = EncryptionManager.Decrypt(ConfigReader.GetInstance().EncryptedAdminUserName);
            //string password = EncryptionManager.Decrypt(ConfigReader.GetInstance().EncryptedAdminPassword);
            credentials.Windows.ClientCredential = new System.Net.NetworkCredential(username, password, ConfigReader.GetInstance().AdminDomain);
            OrganizationServiceProxy orgProxy = new OrganizationServiceProxy(new Uri(ConfigReader.GetInstance().OrganizationUri.ToString()), homeRealmUri, credentials, null);
            orgProxy.Timeout = new TimeSpan(0, 10, 0);
            return orgProxy;

        }
    }
}
